import {messages} from "share/common";
import React, {Component, PropTypes} from 'react';
import { Button, Alert } from 'antd';
import mileageService from '../mileage-service';
import AdvancedTable from 'components/advanced-table';
import SlideFrame from 'components/slide-frame';
import NewLadderModeRule from './new-ladder-mode-rule';
import 'styles/expense-reimbursement-control/mileage-subsidy/new-mileage-subsidy.scss';
import { DataProcessing } from 'containers/expense-reimbursement-control/new-mileage-subsidy/dataSources';
import NewLadderRule from 'containers/expense-reimbursement-control/new-mileage-subsidy/ladder-mode/new-ladder-rule';
import mileageSubsidyService from 'containers/expense-reimbursement-control/mileage-subsidy/mileage-subsidy.service';
import { connect } from 'react-redux';
import menuRoute from "routes/menuRoute";

const { SimpleTable } = AdvancedTable;

@connect(mapStateToProps)
@DataProcessing
class LadderRuleDetail extends Component {

  static propTypes = {
    params: React.PropTypes.object
  };
  static contextTypes = {
    router: PropTypes.object
  };

  ref = null;

  state = {
    columns: ['applicationUserGroupScope', 'currency', 'enabled', 'operation'],
    searchColumns: ['companyNameList', 'enabled'],
    setObj: {
      rule: {
        component: NewLadderRule
      },
      ruleDetail: {
        component: NewLadderModeRule
      }
    },
    ladderModifyStatus: false,
    ruleDetail: {
      stepVOs: []
    }
  };

  componentDidMount() {
    this.handleInitColumns();
    this.getLadderModifyStatus();
  }

  //获取是否修改规则状态
  getLadderModifyStatus = () => {
    const { location: { state: { stepMileageOptId } } } = this.props;
    mileageSubsidyService.getLadderModifyStatus({ stepMileageOptId })
      .then(res => {
        this.setState({ ladderModifyStatus: res.data });
      });
  };

  handleInitColumns = () => {
    let { location: { state: { stepMileageOptId } } } = this.props, { columns } = this.state;
    mileageService.getLadderModeRuleDetail(stepMileageOptId)
      .then(res => {
        columns = ['applicationUserGroupScope', 'currency', 'enabled', 'operation'];
        res.data.stepVOs.forEach((item, index) => {
          columns.splice(2 + index, 0, `stepVOs${item.startUnit}~${item.endUnit === '-1' ? messages('expense-12.key146')/*无限*/ : item.endUnit}`);
        });
        this.setState({ columns, ruleDetail: res.data });
      });
  };

  handleNewRule = (flag, record) => {
    const { setObj, ruleDetail, ruleDetail: { stepVOs } } = this.state;
    stepVOs.map((item, index) => {
      item.unitPrice = record && record.stepVOs[index] ? record.stepVOs[index].unitPrice : void 0;
    });
    SlideFrame.open({
      title: !record ? messages('common.create')/*新建*/ : messages('common.edit')/*编辑*/,
      content: setObj[flag].component,
      afterClose: this.afterCloseSlideFrame,
      hasMask: true,
      params: { // 此处顺序不可改，以record覆盖params
        ...ruleDetail,
        ...record,
        stepVOs
      }
    }, this);
  };

  afterCloseSlideFrame = (ret) => {
    if (ret === 'modeRule') {
      this.ref.getList();
      return;
    }
    if (ret === 'rule') {
      this.handleInitColumns();
    }
  };

  service = (page, size, searchParams) => {
    const { location: { state: { stepMileageOptId } } } = this.props;
    return mileageService.getLadderModeRuleLists({ page, size, stepMileageOptId, ...searchParams });
  };

  handleIndex = (ret) => {
    const nums = ['一', '二', '三', '四', '五', '六', '七', '八', '九'];
    return (ret + '').match(/\d/g)
      .map(() => nums[ret]);
  };

  handleDelete = (record) => {
    mileageService.deleteLadderModeRule(record.stepRuleId)
      .then(() => {
        this.ref.getList();
      });
  };

  goBack = () => {
    let backUrl = menuRoute.getRouteItem('mileage-subsidy', 'key').url;
    this.context.router.push(backUrl + '?tabKey=ladder');
  };

  render() {
    const { columns, searchColumns, ladderModifyStatus, ruleDetail, ruleDetail: { ruleDesc, stepVOs, readOnly } } = this.state;
    return (
      <section className="full-height-page ladder-rule-detail ">
        <section className='ladder-rule-detail-header-box'>
          <section className="ladder-rule-detail-header">
            <h3>
              {messages('expense-12.key147')/*阶梯里程规则*/}
            </h3>
            <Button
              disabled={readOnly || this.isReadOnly()}
              type="primary"
              onClick={() => this.handleNewRule('rule', ruleDetail)}
            >
              {messages('common.edit')/*编辑*/}
            </Button>
          </section>

          <section className="ladder-rule-detail-content">
            <p>{messages('expense-12.key121')/*阶梯里程*/}：{stepVOs.map((item, index) => `${item.startUnit}<${messages('expense-12.key148',{arg1: this.handleIndex(index)})/*第{arg1}阶段*/}<=${item.endUnit === '-1' ? messages('expense-12.key146')/*无限*/ : item.endUnit}，`)}</p>
            <p>{messages('expense-12.key95')/*描述*/}:{ruleDesc}</p>
          </section>

          <Button
            disabled={readOnly || this.isReadOnly()}
            onClick={() => this.handleNewRule('ruleDetail')}
            type="primary"
          >
            {messages('common.create')/*新建*/}
          </Button>

          {
            !!ladderModifyStatus && (
              <Alert
                type="warning"
                style={{ marginTop: '15px' }}
                showIcon
                className="ladder-rule-detail__alert"
                description={messages('expense-12.key149')/*里程阶梯已刷新，请补全各规则中的相应规则，以免影响使用*/}
              />)
          }
        </section>
        <SimpleTable
          onRef={ref => this.ref = ref}
          onRow={record => ({
            onClick: () => this.handleNewRule('ruleDetail', record)
          })}
          rowKey='stepRuleId'
          columns={this.handleColumns(columns)}
          service={this.service}
          searchForm={this.handleSearchForm(searchColumns)}
          footer={
            <Button className="back-btn" onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
          }
        />
      </section>
    );
  }
}

function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
  };
}

export default LadderRuleDetail;
